'''
https://leetcode.cn/problems/largest-bst-subtree
'''
from typing import Optional


# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def largestBSTSubtree(self, root: Optional[TreeNode]) -> int:
        def f(root):
            if not root:
                return True, 0, 0, float('inf'), float('-inf')

            l_isbst, l_size, l_ans, l_min, l_max = f(root.left)
            r_isbst, r_size, r_ans, r_min, r_max = f(root.right)
            isbst = l_isbst and r_isbst and l_max < root.val < r_min
            size = l_size + r_size + 1
            ans = max(l_ans, r_ans, size if isbst else 0)
            minv = min(l_min, root.val, r_min)
            maxv = max(l_max, root.val, r_max)
            return isbst, size, ans, minv, maxv
        return f(root)[2]
